package io.github.hadyang.leetcode.bytedance;

/**
 * 反转链表 反转一个单链表。
 *
 * <p>示例:
 *
 * <p>输入: 1->2->3->4->5->NULL
 *
 * <p>输出: 5->4->3->2->1->NULL
 *
 * @author haoyang.shi
 */
public class Array1038 {

  public ListNode reverseList(ListNode head) {
    if (head == null) {
      return head;
    }

    if (head.next == null) {
      return head;
    }

    ListNode pre = head;
    ListNode cur = head.next;

    while (cur != null) {
      ListNode next = cur.next;
      cur.next = pre;

      pre = cur;
      cur = next;
    }

    head.next = null;

    return pre;
  }

  private static class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
      val = x;
    }

    @Override
    public String toString() {
      return "ListNode{" + "val=" + val + '}';
    }
  }

  public static void main(String[] args) {
    Array1038 main = new Array1038();

    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);

    ListNode node = main.reverseList(head);

    while (node != null) {
      System.out.println(node.val);
      node = node.next;
    }
  }
}
